package com.yixiang.np.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.yixiang.np.annotation.SystemControllerLog;
import com.yixiang.np.model.UFile;
import com.yixiang.np.model.UploadFile;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {
    public static final Logger LOG = LoggerFactory.getLogger(FileController.class);
    private
    @Value("${upload.path}")
    String FILE_PATH;

    //此种上传效率低
    @RequestMapping("/uploadFile")
    public ModelAndView uploadFile(@RequestParam("file") CommonsMultipartFile file) throws Exception { //使用SPRINGMVC中的FILE类去接收，注意如果不用REQUEST需要添加参数注解指明
        System.out.println(file.getSize());
        System.out.println(file.getOriginalFilename());
        if (!file.isEmpty()) {
            FileOutputStream fos = new FileOutputStream(FILE_PATH + new Date().getTime() + "_" + file.getOriginalFilename());
            InputStream in = file.getInputStream();
            int a = 0;
            while ((a = in.read()) != -1) {
                fos.write(a);
            }
            fos.flush();
            fos.close();
            in.close();
        }
        return new ModelAndView("/uploadsuccess");
    }

    //使用SpringMVC的Multipart上传套件来进行上传，效率很高
    @RequestMapping("/speedUploadFile")
    public String speedUploadFile(HttpServletRequest req) throws IllegalStateException, IOException {
        CommonsMultipartResolver cmr = new CommonsMultipartResolver(req.getServletContext());
        //request中是否是Multipart类型数据，如果不是就不处理，是的话就转化成SPRINGMVC中的Mulitipart Request
        if (cmr.isMultipart(req)) {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            //迭代所有文件
            Iterator<String> it = mreq.getFileNames();
            while (it.hasNext()) {
                //使用SpringMVC中的FILE
                MultipartFile file = mreq.getFile(it.next());
                if (!file.isEmpty()) {
                    System.out.println(file.getOriginalFilename());
                    String fileName = "Upload_" + file.getOriginalFilename();
                    String path = FILE_PATH + fileName;

                    File localFile = new File(path);
                    //使用SpringMVC中的Multipart File来存储文件
                    file.transferTo(localFile);
                }
            }
        }
        return "/uploadsuccess";
    }

    //使用AJAX上传文件，支持多文件上传，已与Plupload2.1.2插件测试通过
    @RequestMapping("/ajaxLoadFile")
    @ResponseBody
    @SystemControllerLog(module = "通用模块", methods = "上传附件")
    public Object ajaxLoadFile(HttpServletRequest req, HttpServletResponse res) throws IllegalStateException, IOException {
        CommonsMultipartResolver cmr = new CommonsMultipartResolver(req.getServletContext());
        Map<String, Object> hm = new HashMap<String, Object>();
        //request中是否是Multipart类型数据，如果不是就不处理，是的话就转化成SPRINGMVC中的Mulitipart Request
        if (cmr.isMultipart(req)) {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            //迭代所有文件
            Iterator<String> it = mreq.getFileNames();
            while (it.hasNext()) {
                //使用SpringMVC中的FILE
                MultipartFile file = mreq.getFile(it.next());
                if (!file.isEmpty()) {
                    System.out.println(file.getOriginalFilename());
//					String dateStr = DateUtil.getDate(new Date());
//					String fileName = "Upload_"+file.getOriginalFilename();
                    String orgName = file.getOriginalFilename();
                    String prefix = orgName.substring(orgName.lastIndexOf("."));
                    String fileName = UUID.randomUUID().toString() + prefix;
                    String dir = FILE_PATH;
                    if (!new File(dir).exists()) {
                        new File(dir).mkdirs();
                    }
                    String path = dir + File.separator + fileName;

                    File localFile = new File(path);
                    //使用SpringMVC中的Multipart File来存储文件
                    file.transferTo(localFile);
                    hm.put("msg", fileName);
                }
            }
        }
        return hm;
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse res, String filePath) throws IOException {
        OutputStream os = res.getOutputStream();
        try {
            File file = new File(filePath);
            if (file != null) {
                res.reset();
                res.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                res.setContentType("application/octet-stream; charset=utf-8");
                String fileName = FILE_PATH + filePath;
                os.write(FileUtils.readFileToByteArray(new File(fileName)));
                os.flush();
            }
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    @RequestMapping(value = "/imUploadFile")
    public
    @ResponseBody
    UploadFile upload(@RequestParam(value = "file", required = false) MultipartFile file, int userId, HttpServletRequest request) {
        UploadFile upFile = new UploadFile();
        String path = FILE_PATH;
        String fileName = file.getOriginalFilename();
        /**获取文件的后缀**/
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + suffix;
        File pathName = new File(path);
        File targetFile = new File(path, name);
        if (!pathName.exists()) {
            pathName.mkdirs();
        }
        try {
            String pro = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + pro + "/";
            file.transferTo(targetFile);
            upFile.setCode(0);
            UFile uf = new UFile();
            uf.setName(fileName);
            uf.setSrc(basePath + "file/download?filePath=" + name);
            upFile.setData(uf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return upFile;
    }

    @RequestMapping("/uploadRegPic")
    public
    @ResponseBody
    UploadFile uploadHeadPic(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        UploadFile upFile = new UploadFile();
        String path = FILE_PATH;
        String fileName = file.getOriginalFilename();
        /**获取文件的后缀**/
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + suffix;
        File pathName = new File(path);
        File targetFile = new File(path, name);
        if (!pathName.exists()) {
            pathName.mkdirs();
        }
        try {
            String pro = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + pro + "/";
            file.transferTo(targetFile);
            upFile.setCode(0);
            UFile uf = new UFile();
            uf.setName(fileName);
            uf.setSrc(basePath + "file/download?filePath=" + name);
            upFile.setData(uf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return upFile;
    }
 
}